package cn.sunshine.ymcc.mq.consumer;

import cn.sunshine.ymcc.domain.MediaFile;
import cn.sunshine.ymcc.mapper.MediaFileMapper;
import cn.sunshine.ymcc.result.JSONResult;
import cn.sunshine.ymcc.service.IMediaFileService;
import cn.sunshine.ymcc.service.impl.MediaFileServiceImpl;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import feign.form.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.MessageModel;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

@Slf4j
@Component
@RocketMQMessageListener(topic = "topic-media", // topic
        selectorExpression="tags-media"	//tags
        ,consumerGroup = "service-media-consumer" // 消费者组
        ,messageModel = MessageModel.CLUSTERING ) // 消费者模型，有广播和集群 BROADCASTING("BROADCASTING"),CLUSTERING("CLUSTERING");
public class MediaConsumer implements RocketMQListener<MessageExt> {
    @Autowired
    private IMediaFileService mediaFileService;
    @Override
    @Transactional
    // 这里拿到消息
    public void onMessage(MessageExt message) { // MessageExt这是消息的包装类
        String msg = new String(message.getBody(), CharsetUtil.UTF_8); // ALT 常量。否则要报错。
        log.info("消费者 {} ", msg);
        MediaFile mediaFile = JSONObject.parseObject(msg, MediaFile.class);
        System.out.println(mediaFile);
        JSONResult jsonResult = mediaFileService.handleFile2m3u8(mediaFile);
        if (jsonResult.isSuccess()){
            mediaFile.setFileStatus(2);
        }else {
            mediaFile.setFileStatus(3);
        }
        mediaFileService.updateById(mediaFile);
    }
}
